package com.dlyk.manager;

import com.dlyk.mapper.TClueMapper;
import com.dlyk.mapper.TCustomerMapper;
import com.dlyk.model.TActivityRemark;
import com.dlyk.model.TClue;
import com.dlyk.model.TCustomer;
import com.dlyk.query.CustomerQuery;
import com.dlyk.util.JWTUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @description:
 * @author: ajie
 * @date: 2024/7/29 23:40:28
 * @version: 1.0
 */
@Component
public class CustomerManager {

    @Resource
    private TCustomerMapper tCustomerMapper;

    @Resource
    private TClueMapper tClueMapper;

    @Transactional(rollbackFor = Exception.class)
    public Boolean convertCustomer(CustomerQuery customerQuery) {
        //验证该线索是否已经转过客户，转过就不能再转
        TClue tClue = tClueMapper.selectByPrimaryKey(customerQuery.getClueId());
        if (tClue.getState() == -1){
            throw new RuntimeException("该线索已经转过客户，不能再转了");
        }
        //向客户表插入一条数据
        TCustomer tCustomer = new TCustomer();

        BeanUtils.copyProperties(customerQuery,tCustomer);

        tCustomer.setCreateTime(new Date());//创建时间

        ///登陆人的id
        Integer loginUserId = JWTUtils.parseJWTByUserId(customerQuery.getToken());
        tCustomer.setCreateBy(loginUserId);//创建人
        int insert = tCustomerMapper.insertSelective(tCustomer);

        //把线索表的数据状态改为-1（已转客户）
        TClue clue = new TClue();
        clue.setId(customerQuery.getClueId());
        clue.setState(-1);
        int update = tClueMapper.updateByPrimaryKeySelective(clue);
        return insert >= 1 && update >= 1;
    }
}
